<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" label-width="120px">
      <el-form-item label="名称" prop="title">
        <el-input v-model="dataForm.title" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item label="封面图" prop="pic">
        <el-upload class="avatar-uploader" :action="url" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.pic" :src="dataForm.pic" class="avatar" />
          <el-icon v-else class="el-icon--upload" style="width: 200px"><upload-filled /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序" prop="title">
        <el-input-number v-model="dataForm.orderNum" placeholder="排序"></el-input-number>
      </el-form-item>
      <el-form-item label="详情" prop="details">
        <!-- 富文本编辑器, 容器 -->
        <editor v-model="dataForm.details" :init="{ height: 300 }"></editor>
        <!-- 自定义上传图片功能 (使用element upload组件) -->
        <el-upload :action="url" :show-file-list="false" :before-upload="uploadBeforeUploadHandle" :on-success="uploadSuccessHandle" style="display: none">
          <el-button ref="uploadBtn" type="primary" size="small">{{ $t("upload.button") }}</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="教学目标" prop="target">
        <el-input v-model="dataForm.target" placeholder="教学目标"></el-input>
      </el-form-item>
      <el-form-item label="上传视频" prop="videoList">
        <el-upload :action="url" :file-list="dataForm.videoList" drag :before-upload="beforeUploadHandleVido" :on-success="successHandle3" :on-preview="downFile" :on-remove="onRemove" class="text-center">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>

          <div class="el-upload__text" v-html="$t('upload.text')"></div>
        </el-upload>
      </el-form-item>
      <el-form-item label="添加视频链接" prop="vidioUrl">
        <el-row>
          <el-col :span="10">
            <el-input v-model="video.url" placeholder="视频链接"></el-input>
          </el-col>
          <el-col :span="10">
            <el-input v-model="video.name" placeholder="视频名称"> </el-input>
          </el-col>
          <el-col :span="4">
            <el-button @click="addVideo">添加</el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="上传课件" prop="createAt">
        <el-upload v-loading="fileLoading" :action="url2" :file-list="dataForm.fileList" drag :before-upload="beforeUploadHandle" :on-success="successHandle" :on-preview="downFile" :on-remove="onRemove2" class="text-center">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text" v-html="$t('upload.text')"></div>
        </el-upload>
        <!--        <el-button @click="uploadClass()">添加课件</el-button>-->
      </el-form-item>

      <el-form-item label="添加课件链接" prop="vidioUrl">
        <el-row>
          <el-col :span="10">
            <el-input v-model="file.url" placeholder="课件链接"></el-input>
          </el-col>
          <el-col :span="10">
            <el-input v-model="file.name" placeholder="课件名称"> </el-input>
          </el-col>
          <el-col :span="4">
            <el-button @click="addFile">添加</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
    <!-- 弹窗, 上传文件 -->
    <upload v-if="uploadVisible" ref="upload" @refreshDataList="getDataList"></upload>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
import baseService from "@/service/baseService";
import { useDebounce } from "@/utils/utils";
import Upload from "./oss-upload.vue";
import { IObject } from "@/types/interface";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import useView from "@/hooks/useView";
import Tinymce from "@/components/tinymce";
export default defineComponent({
  components: {
    Upload,
    editor: Tinymce
  },
  setup() {
    const state = reactive({
      visible: false,
      fileLoading: false,
      picUploadUrl: "",
      url: "",
      url2: "",
      file: { url: "", name: "" },
      video: { url: "", name: "" },
      num: 0,
      //picUploadUrl:"",
      uploadUrl: "",
      //富文本结束
      uploadVisible: false,
      dataForm: {
        id: "",
        pic: "",
        courseId: "",
        title: "",
        details: "",
        target: "",
        createAt: "",
        creator: "",
        updateAt: "",
        orderNum: 0,
        videoList: [] as IObject[],
        fileList: [] as IObject[],
        updator: ""
      }
    });
    return { ...useView(state), ...toRefs(state) };
  },
  computed: {
    dataRule() {
      return {};
    }
  },
  created() {
    this.dataFormSubmitHandle = useDebounce(this.dataFormSubmitHandle);
  },
  methods: {
    init() {
      this.visible = true;
      this.visible = true;
      this.url = `${app.api}/fii/fiiclasshourfile/upload?token=${getToken()}`; //上传视频地址
      this.url2 = `${app.api}/fii/fiiclasshourfile/upload?&fileType=kejian&token=${getToken()}`; //上传课件地址
      this.num = 0;

      this.$nextTick(() => {
        this.$refs["dataFormRef"].resetFields();

        //清空上传文件
        this.dataForm.fileList = [];
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    uploadClass() {
      this.uploadVisible = true;
    },
    // 获取信息
    getInfo() {
      baseService.get("/fii/fiiclasshour/" + this.dataForm.id).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.dataForm = res.data;
      });
    },
    // 表单提交
    dataFormSubmitHandle() {
      this.$refs["dataFormRef"].validate((valid: boolean) => {
        if (!valid) {
          return false;
        }
        (!this.dataForm.id ? baseService.post : baseService.put)("/fii/fiiclasshour", this.dataForm).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$message({
            message: this.$t("prompt.success"),
            type: "success",
            duration: 500,
            onClose: () => {
              this.visible = false;
              this.$emit("refreshDataList");
            }
          });
        });
      });
    },
    beforeUploadHandleVido(file: IObject) {
      if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
        //  this.$message.error(this.$t("upload.tip", { format: "jpg、png、gif" }));
        // return false;
      }
      this.num++;
    },
    // 上传之前
    beforeUploadHandle(file: IObject) {
      if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
        //  this.$message.error(this.$t("upload.tip", { format: "jpg、png、gif" }));
        // return false;2
      }
      this.fileLoading = true;
      this.num++;
    },
    // 上传成功
    successHandle(res: IObject, file: IObject, fileList: IObject[]) {
      this.$nextTick(() => {
        // 以服务的方式调用的 Loading 需要异步关闭
        this.fileLoading = false;
      });
      if (res.code !== 0) {
        this.$message.error(res.msg);
        return false;
      } else {
        file.url = res.data.file.url;
        file.id = res.data.file.id;
        this.dataForm.fileList = fileList;
        this.num--;
        console.log(fileList);
      }

      if (this.num === 0) {
        this.$message({
          message: this.$t("prompt.success"),
          type: "success",
          duration: 500,
          onClose: () => {
            //this.visible = false;
            //this.$emit("refreshDataList");
          }
        });
      }
    },
    // 上传成功
    successHandle3(res: IObject, file: IObject, fileList: IObject[]) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      file.url = res.data.file.url;
      file.id = res.data.file.id;
      this.num--;
      this.dataForm.videoList = fileList;
      console.log(fileList);
      if (this.num === 0) {
        this.$message({
          message: this.$t("prompt.success"),
          type: "success",
          duration: 500,
          onClose: () => {
            //this.visible = false;
            //this.$emit("refreshDataList");
          }
        });
      }
    },
    onRemove(file: IObject, fileList: IObject[]) {
      console.log(file);
      console.log(fileList);
      this.dataForm.videoList = fileList;
    },
    onRemove2(file: IObject, fileList: IObject[]) {
      console.log(file);
      console.log(fileList);
      this.dataForm.fileList = fileList;
    },
    downFile(file: IObject) {
      alert(file.name);
    },
    isURL(s: string) {
      return /^http[s]?:\/\/.*/.test(s);
    },
    addVideo() {
      if (!this.video.url) {
        this.$message.error("地址不能为空！");
        return;
      }
      if (!this.isURL(this.video.url)) {
        this.$message.error("地址不合法！");
        return;
      }
      if (!this.video.name) {
        this.$message.error("名称不能为空！");
        return;
      }
      if (this.video.url && this.video.name) {
        this.dataForm.videoList.push({ url: this.video.url, name: this.video.name, type: 1 });
        this.video.url = "";
        this.video.name = "";
        this.$message.success("添加成功！");
      }
    },
    addFile() {
      if (!this.file.url) {
        this.$message.error("地址不能为空！");
        return;
      }
      if (!this.isURL(this.file.url)) {
        this.$message.error("地址不合法！");
        return;
      }
      if (!this.file.name) {
        this.$message.error("名称不能为空！");
        return;
      }
      if (this.file.url && this.file.name) {
        this.dataForm.fileList.push({ url: this.file.url, name: this.file.name, type: 2 });
        this.file.url = "";
        this.file.name = "";
        this.$message.success("添加成功！");
      }
    },
    // 富文本上传图片之前
    uploadBeforeUploadHandle(file: IObject) {
      if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
        this.$message.error(this.$t("upload.tip", { format: "jpg、png、gif" }));
        return false;
      }
    },
    //  富文本上传图片成功
    uploadSuccessHandle(res: IObject) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
    },
    beforeAvatarUpload(file: IObject) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 4;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 4MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res: IObject, file: IObject) {
      this.dataForm.pic = res.data.file.url;
    }
  }
});
</script>
